<template>

  <div><van-nav-bar title="访销助手" class="page-nav-bar" /></div>

  <div class="login-container">
    <div class="login-card">
      <p class="subtitle">请输入您的账号和密码</p>
      <!-- 全局变量配置 -->
      <van-config-provider>
        <van-form @submit="submitForm" ref="loginForm" class="login-form">
          <van-field v-model="form.username" size='large' name="username" label="账号" placeholder="请输入账号"
            :rules="[{ required: true, message: '请输入账号' }]">
            <template #left-icon>
              <van-icon name="user-o" />
            </template>
          </van-field>
          <van-field v-model="form.password" type="password" size='large' name="password" label="密码" placeholder="请输入密码"
            :rules="[{ required: true, message: '请输入密码' }]">
            <template #left-icon>
              <van-icon name="lock" />
            </template>
          </van-field>
          <div style="margin: 16px;">
            <van-button round block size="large" type="primary" native-type="submit" :loading="loading">
              登录
            </van-button>
          </div>
        </van-form>
      </van-config-provider>
      <div class="extra-links">
        <a>忘记密码？请联系管理员(陈震)</a><br>
        <!-- <router-link to="/register">新用户点击此处注册账号</router-link> -->
      </div>
    </div>
  </div>
</template>

<script>
import { login } from '@/api/index'; // 假设你的 API 服务在这个路径

export default {
  data() {
    return {
      form: {
        username: '',
        password: ''
      },
      loading: false // 添加 loading 变量
    };
  },
  methods: {
    async submitForm() {
      try {
        this.loading = true;
        await login(this.form); // 调用登录接口
        // 登录成功后将账号和密码存储到 localStorage 中
        localStorage.setItem('username', this.form.username);
        localStorage.setItem('password', this.form.password);
        this.$router.push('/mystore'); // 假设登录成功后跳转到仪表盘
      } catch (error) {
        showDialog({
          title: '登录失败',
          message: '用户名或密码错误或网络有问题',
          theme: 'round-button',
          confirmButtonText: '确定',
          onConfirm: () => {
            // 弹窗关闭后跳转到登录页面
            this.$router.push('/login');
          }
        })
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>

<style>
.login-container input {
  touch-action: none;
}
</style>
